package com.cryann.mqttserver.mqttProcess.mqttMsgHandler;

import com.cryann.mqttserver.exception.MqttException;
import com.google.common.collect.ImmutableSet;
import io.netty.handler.codec.mqtt.MqttFixedHeader;
import io.netty.handler.codec.mqtt.MqttMessage;
import io.netty.handler.codec.mqtt.MqttMessageType;
import io.netty.handler.codec.mqtt.MqttQoS;
import org.springframework.stereotype.Component;

import java.util.Set;

/**
 * @author cRyann
 * @date 2018/12/29 0029 09:02
 * @description:
 */
@Component
public class MQTT_3$1$2_3 extends AbstractMqttHandler {
    @Override
    protected Set<MqttMessageType> handlerType() {
        Set<MqttMessageType> set = ImmutableSet.of(MqttMessageType.CONNECT);
        return set;
    }

    @Override
    protected boolean checkMsg(MqttMessage request) {
        MqttFixedHeader fixedHeader = request.fixedHeader();
        if ( fixedHeader.isRetain() ) {
            throw new MqttException("[MQTT-3.1.2-3] 服务端必须验证 CONNECT 控制报文的保留标志位（第 0 位）是否为 0，如果不为 0 必须断开客户端连接。");
        } else if ( !fixedHeader.qosLevel().equals(MqttQoS.AT_MOST_ONCE) || fixedHeader.isDup() ) {
            throw new MqttException("服务端必须验证 CONNECT 控制报文的保留标志位（第 0 位）是否为 0，如果不为 0 必须断开客户端连接。");
        }

        return true;
    }
}
